<template>
  <dialog ref="dialogRef" class="mini-dialog" @close="onCloseInternal">
    <form method="dialog" class="dialog-body" @submit.prevent>
      <header class="mini-header">
        <h3 class="title with-icon"><span class="dlg-icon">
          <svg viewBox="0 0 24 24" stroke="currentColor" fill="none"><circle cx="12" cy="12" r="9" stroke-width="1.6"/><path d="M12 8v8M12 6v.5M12 16v1.5" stroke-width="1.6" stroke-linecap="round"/></svg>
        </span>产品属性</h3>
        <button type="button" class="ui-close-btn" @click="close" aria-label="关闭">
          <svg class="icon-x" viewBox="0 0 24 24" fill="none"><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>
        </button>
      </header>
      <section class="content" v-if="sku">
        <div class="top-basic">
          <div class="img-box" v-if="sku.mainImageUrl"><img :src="sku.mainImageUrl" :alt="sku.code" /></div>
          <div class="meta">
            <h4 class="prod-name">{{ sku.name || sku.code }}</h4>
            <p class="prod-sub">分类：{{ sku.category }} · 状态：<span :class="['status', sku.status]">{{ sku.status==='pending'?'待维护':'已完成' }}</span></p>
            <p class="timestamps">创建：{{ formatDate(sku.createdAt) }} · 更新：{{ formatDate(sku.updatedAt) }}</p>
          </div>
        </div>
        <div v-if="attrPairs.length" class="attr-grid enhanced">
          <div v-for="(pair,i) in attrPairs" :key="i" class="attr-item" :class="[pair.from==='override' ? 'dyn' : 'loc']" :title="pair.display">
            <span class="k">{{ pair.key }}<span v-if="pair.from==='override'" class="src-badge" aria-label="动态属性">D</span></span>
            <span class="v">{{ pair.display }}</span>
          </div>
        </div>
        <p v-else class="empty">暂无属性</p>
      </section>
      <section v-else class="content loading">加载中...</section>
      <footer class="mini-actions">
        <button class="btn primary" type="button" @click="close">关闭</button>
      </footer>
    </form>
  </dialog>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { useSkuStore, SkuProductBase } from '../../../store/sku';
const dialogRef = ref<HTMLDialogElement|null>(null);
const skuCode = ref<string>('');
const overrideAttributes = ref<Record<string, any>|null>(null);
const loadError = ref('');
const skuStore = useSkuStore();
const sku = computed<SkuProductBase | undefined>(() => skuStore.getProduct(skuCode.value));

interface AttrPair { key:string; display:string; from:'local'|'override'; raw:any }
const attrPairs = computed<AttrPair[]>(() => {
  const prod = sku.value;
  const local = prod?.attributes || {};
  const over = overrideAttributes.value || {};
  const map: Record<string, AttrPair> = {};
  if (prod) {
    if (prod.name) map['品名'] = { key: '品名', display: prod.name, raw: prod.name, from: 'local' };
    if (prod.code) map['编码'] = { key: '编码', display: prod.code, raw: prod.code, from: 'local' };
  }
  for (const [k, v] of Object.entries(local)) {
    let display = '';
    if (v && typeof v === 'object' && 'value' in (v as any)) {
      const obj = v as any; display = obj.unit ? `${obj.value}${obj.unit}` : String(obj.value);
    } else display = String(v);
    map[k] = { key: k, display, raw: v, from: 'local' };
  }
  for (const [k, v] of Object.entries(over)) {
    let display = '';
    if (v && typeof v === 'object' && 'value' in (v as any)) {
      const obj = v as any; display = obj.unit ? `${obj.value}${obj.unit}` : String(obj.value);
    } else display = String(v);
    map[k] = { key: k, display, raw: v, from: 'override' };
  }
  // 过滤纯英文属性（如果 key 全是英文字母则需要包含中文才保留）
  const arr = Object.values(map).filter(p => /[a-zA-Z]/.test(p.key) ? /[\u4e00-\u9fa5]/.test(p.key) : true);
  const headKeys = ['品名', '编码'].filter(k => k in map);
  const head = headKeys.map(k => map[k]);
  const tail = arr.filter(p => !headKeys.includes(p.key)).sort((a, b) => a.key.localeCompare(b.key, 'zh-Hans-CN'));
  return [...head, ...tail];
});

function formatDate(ts:number){ const d=new Date(ts); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }

function open(row: { code:string }, attrsOverride?: Record<string, any>, errorMsg?: string) {
  skuCode.value = row.code;
  overrideAttributes.value = attrsOverride || null;
  loadError.value = errorMsg || '';
  const el=dialogRef.value; if(el){ el.showModal(); }
}
function close(){ const el=dialogRef.value; if(el) el.close(); }
function onCloseInternal(){ skuCode.value=''; overrideAttributes.value=null; loadError.value=''; }
defineExpose({ open });
</script>
<style scoped>
.mini-dialog::backdrop { background:rgba(0,0,0,.4); }
.mini-dialog { border:none; padding:0; border-radius:16px; width:560px; max-width:92vw; box-shadow:0 12px 32px -8px rgba(0,0,0,.3); }
.dialog-body { display:flex; flex-direction:column; max-height:70dvh; background:#fff; }
.mini-header { display:flex; justify-content:space-between; align-items:center; padding:.9rem 1.1rem; border-bottom:1px solid #e2e8f0; }
.title { margin:0; font-size:18px; font-weight:600; display:flex; align-items:center; gap:.55rem; }
.title.with-icon .dlg-icon { width:22px; height:22px; color:#334155; background:#f1f5f9; border:1px solid #e2e8f0; display:inline-flex; align-items:center; justify-content:center; border-radius:6px; }
.title.with-icon .dlg-icon svg { width:15px; height:15px; }
.content { padding:1rem 1.1rem 1.3rem; overflow:auto; display:flex; flex-direction:column; gap:1rem; }
.top-basic { display:flex; gap:1rem; }
.img-box { width:140px; flex-shrink:0; border:1px solid #e2e8f0; border-radius:12px; overflow:hidden; background:#f1f5f9; display:flex; align-items:center; justify-content:center; }
.img-box img { width:100%; height:auto; display:block; }
.prod-name { margin:.2rem 0 .4rem; font-size:18px; font-weight:700; letter-spacing:.02em; }
.prod-sub, .timestamps { margin:0; font-size:12px; color:#64748b; }
.status { padding:.15rem .5rem; border-radius:12px; font-size:12px; background:#e2e8f0; }
.status.pending { background:#fde68a; color:#92400e; }
.status.completed { background:#bbf7d0; color:#166534; }
.attr-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,1fr)); gap:.7rem .9rem; }
.attr-grid.enhanced { grid-template-columns:repeat(auto-fill,minmax(170px,1fr)); }
.attr-item { position:relative; display:flex; flex-direction:column; background:linear-gradient(145deg,#ffffff,#f8fafc 75%); border:1px solid #e2e8f0; border-radius:14px; padding:.65rem .7rem .7rem; box-shadow:0 6px 18px -8px rgba(15,23,42,.15),0 2px 6px -2px rgba(15,23,42,.08); transition:box-shadow .35s, transform .35s; }
.attr-item:before { content:""; position:absolute; inset:0; border-radius:inherit; background:radial-gradient(circle at 28% 22%,rgba(255,255,255,.6),transparent 70%); mix-blend-mode:overlay; pointer-events:none; }
.attr-item:hover { transform:translateY(-6px); box-shadow:0 14px 34px -12px rgba(59,130,246,.35),0 6px 18px -6px rgba(59,130,246,.25); }
.attr-item.dyn { background:linear-gradient(145deg,#eff6ff,#ffffff 70%); border-color:#93c5fd; }
.attr-item.dyn .k { color:#1d4ed8; }
.attr-item .k { font-size:11px; font-weight:600; color:#475569; letter-spacing:.05em; text-transform:uppercase; display:flex; align-items:center; gap:4px; }
.attr-item .v { font-size:13px; font-weight:600; color:#0f172a; word-break:break-word; }
.attr-item .src-badge { display:inline-block; padding:2px 5px 3px; font-size:10px; line-height:1; background:#2563eb; color:#fff; border-radius:8px; font-weight:600; letter-spacing:.05em; box-shadow:0 2px 4px -2px rgba(15,23,42,.4); }
.empty { margin:0; color:#64748b; font-size:14px; }
.loading { font-size:14px; color:#64748b; }
.mini-actions { display:flex; justify-content:flex-end; gap:.6rem; padding:.7rem 1.1rem .9rem; border-top:1px solid #e2e8f0; }
.btn { cursor:pointer; border:1px solid #2563eb; background:#3b82f6; color:#fff; padding:.55rem 1rem; border-radius:10px; font-size:13px; font-weight:600; }
.btn:hover { background:#2563eb; }
</style>
